#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
流管理API
"""

from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from app.core.database import get_db
from app.models.stream import Stream, StreamStatus
from app.schemas.stream import StreamCreate, StreamUpdate, StreamResponse
from app.services.stream_monitor import get_stream_monitor
from app.api.auth import get_current_user_id

router = APIRouter()

# 创建流监控实例
stream_monitor = get_stream_monitor()

@router.post("/streams")
async def create_stream(
    stream: StreamCreate,
    db: Session = Depends(get_db),
    current_user_id: int = Depends(get_current_user_id)
):
    """创建新的直播流"""
    from datetime import datetime
    
    db_stream = Stream(**stream.dict())
    # 创建流时默认状态为INACTIVE
    db_stream.status = StreamStatus.INACTIVE
    db_stream.updated_at = datetime.now()  # 设置更新时间
    db_stream.act_uid = current_user_id  # 使用当前用户ID
    db.add(db_stream)
    db.commit()
    db.refresh(db_stream)
    
    # 刷新流监控 - 让定时刷新机制处理
    await stream_monitor._refresh_streams_from_db()
    
    return {
        "code": 200,
        "message": "直播流创建成功",
        "data": {
            "id": db_stream.id,
            "name": db_stream.name,
            "url": db_stream.url,
            "status": db_stream.status,
            "description": db_stream.description,
            "resolution": db_stream.resolution,
            "bitrate": db_stream.bitrate,
            "fps": db_stream.fps,
            "video_codec": db_stream.video_codec,
            "audio_codec": db_stream.audio_codec,
            "act_uid": db_stream.act_uid,
            "stream_type": db_stream.stream_type,
            "is_recording": db_stream.is_recording,
            "is_pushing": db_stream.is_pushing,
            "created_at": db_stream.created_at.isoformat() if db_stream.created_at else None,
            "updated_at": db_stream.updated_at.isoformat() if db_stream.updated_at else None
        }
    }

@router.put("/streams/{stream_id}")
async def update_stream(
    stream_id: int,
    stream_update: StreamUpdate,
    db: Session = Depends(get_db)
):
    """更新直播流"""
    stream = db.query(Stream).filter(Stream.id == stream_id).first()
    if not stream:
        raise HTTPException(status_code=404, detail="直播流不存在")
    
    for field, value in stream_update.dict(exclude_unset=True).items():
        setattr(stream, field, value)
    
    db.commit()
    db.refresh(stream)
    
    # 刷新流监控 - 使用刷新机制
    await stream_monitor._refresh_streams_from_db()
    
    return {
        "code": 200,
        "message": "直播流更新成功",
        "data": {
            "id": stream.id,
            "name": stream.name,
            "url": stream.url,
            "status": stream.status,
            "description": stream.description,
            "resolution": stream.resolution,
            "bitrate": stream.bitrate,
            "fps": stream.fps,
            "video_codec": stream.video_codec,
            "audio_codec": stream.audio_codec,
            "act_uid": stream.act_uid,
            "stream_type": stream.stream_type,
            "is_recording": stream.is_recording,
            "is_transcode": stream.is_transcode,
            "is_pushing": stream.is_pushing,
            "created_at": stream.created_at.isoformat() if stream.created_at else None,
            "updated_at": stream.updated_at.isoformat() if stream.updated_at else None
        }
    }

@router.get("/streams/list")
async def get_streams(
    page: int = Query(1, ge=1, description="页码"),
    limit: int = Query(20, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="流名称模糊搜索"),
    status: Optional[str] = Query(None, description="状态筛选"),
    db: Session = Depends(get_db)
):
    """获取流列表 - 统一返回格式"""
    try:
        query = db.query(Stream).filter(Stream.inuse == 1)  # 只显示inuse=1的流
        if name:
            query = query.filter(Stream.name.contains(name))
        if status:
            query = query.filter(Stream.status == status)
        
        # 获取总数
        total = query.count()
        
        # 获取分页数据
        streams = query.offset((page - 1) * limit).limit(limit).all()
        
        # 转换为响应格式
        items = []
        for stream in streams:
            items.append({
                "id": stream.id,
                "name": stream.name,
                "url": stream.url,
                "status": stream.status,
                "description": stream.description,
                "resolution": stream.resolution,
                "bitrate": stream.bitrate,
                "fps": stream.fps,
                "video_codec": stream.video_codec,
                "audio_codec": stream.audio_codec,
                "act_uid": stream.act_uid,
                "stream_type": stream.stream_type,
                "is_recording": stream.is_recording,
                "is_transcode": stream.is_transcode,
                "is_pushing": stream.is_pushing,
                "created_at": stream.created_at.isoformat() if stream.created_at else None,
                "updated_at": stream.updated_at.isoformat() if stream.updated_at else None
            })
        
        return {
            "code": 200,
            "data": {
                "items": items,
                "total": total
            },
            "message": "success"
        }
    except Exception as e:
        return {
            "code": 500,
            "data": None,
            "message": str(e)
        }

@router.get("/streams/{stream_id}")
async def get_stream(
    stream_id: int,
    db: Session = Depends(get_db)
):
    """获取单个直播流详情"""
    stream = db.query(Stream).filter(Stream.id == stream_id, Stream.inuse == 1).first()
    if not stream:
        raise HTTPException(status_code=404, detail="直播流不存在")
    return {
        "code": 200,
        "message": "success",
        "data": {
            "id": stream.id,
            "name": stream.name,
            "url": stream.url,
            "status": stream.status,
            "description": stream.description,
            "resolution": stream.resolution,
            "bitrate": stream.bitrate,
            "fps": stream.fps,
            "video_codec": stream.video_codec,
            "audio_codec": stream.audio_codec,
            "act_uid": stream.act_uid,
            "stream_type": stream.stream_type,
            "is_recording": stream.is_recording,
            "is_transcode": stream.is_transcode,
            "is_pushing": stream.is_pushing,
            "created_at": stream.created_at.isoformat() if stream.created_at else None,
            "updated_at": stream.updated_at.isoformat() if stream.updated_at else None
        }
    }

@router.post("/streams/{stream_id}/start")
async def start_stream(
    stream_id: int,
    db: Session = Depends(get_db)
):
    """启动直播流"""
    stream = db.query(Stream).filter(Stream.id == stream_id, Stream.inuse == 1).first()
    if not stream:
        raise HTTPException(status_code=404, detail="直播流不存在")
    
    stream.status = StreamStatus.INACTIVE
    db.commit()
    
    # 重新添加流监控 - 使用刷新机制
    await stream_monitor._refresh_streams_from_db()
    
    return {"message": "直播流已启动", "status": "inactive"}

@router.post("/streams/{stream_id}/stop")
async def stop_stream(
    stream_id: int,
    db: Session = Depends(get_db)
):
    """停止直播流"""
    stream = db.query(Stream).filter(Stream.id == stream_id, Stream.inuse == 1).first()
    if not stream:
        raise HTTPException(status_code=404, detail="直播流不存在")
    
    stream.status = StreamStatus.ERROR
    db.commit()
    
    # 停止流监控 - 使用刷新机制
    await stream_monitor._refresh_streams_from_db()
    
    return {"message": "直播流已停止", "status": "error"}

@router.delete("/streams/{stream_id}")
async def delete_stream(
    stream_id: int,
    db: Session = Depends(get_db)
):
    """删除直播流"""
    stream = db.query(Stream).filter(Stream.id == stream_id, Stream.inuse == 1).first()
    if not stream:
        raise HTTPException(status_code=404, detail="直播流不存在")
    
    # 检查是否有任务在使用此流
    from app.models.task import Task
    active_tasks = db.query(Task).filter(
        Task.stream_id == stream_id,
        Task.inuse == 1,
        Task.status.in_(["running", "pending"])
    ).count()
    
    if active_tasks > 0:
        raise HTTPException(status_code=400, detail="该流有关联的任务正在运行，无法删除")
    
    # 软删除，将inuse设为0
    stream.inuse = 0
    db.commit()
    
    # 刷新流监控 - 使用刷新机制
    await stream_monitor._refresh_streams_from_db()
    
    return {"message": "直播流已删除"}